package br.com.sig.presentation.converter;

import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 * Converter CEP
 *
 */
@FacesConverter(value = "cepConverter")
@RequestScoped
public class CepConverter implements Converter {

	public Object getAsObject(FacesContext context, UIComponent ui, String value) {
		if (value == null) {
			return value;
		}

		return value.replaceAll("\\.|-", "");
	}

	public String getAsString(FacesContext context, UIComponent ui, Object obj) {
		if (obj == null) {
			return null;
		}

		String str = (String) obj;
		if (str.length() == 8) {
			str = str.substring(0, 2) + str.substring(2, 5) + "-" + str.substring(5, 8);
		}

		return str;
	}

}